package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.util.CartRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Iterator;

@Controller
@RequestMapping("/cart")
@SessionAttributes("cart")
public class CartController {

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private CartService cartService;

    @Autowired
    Cart cart;

    @GetMapping("/viewCart")
    public String viewCart(HttpSession session, Model model) {
        cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            session.setAttribute("cart", cart);
            model.addAttribute("cart",cart);
        }
        return "/cart/Cart";
    }

    @GetMapping("/addItemToCart")
    public String addItemToCart(HttpSession session, String workingItemId, Model model){
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            model.addAttribute("cart", cart);
        }
        Account account = (Account)session.getAttribute("account");

        if (account == null) {
            model.addAttribute("msg", "请先登录");
            return "/account/SignonForm";
        }
        String userid = account.getUsername();
        if (cart.containsItemId(workingItemId)) {
            //此物品已存在
            int quantity = cartService.getQuantityByItemidAndUserid(account.getUsername(), workingItemId);
            quantity++;//数量加一
            BigDecimal price = cartService.getListPriceByItemidAndUserid(account.getUsername(), workingItemId);
            BigDecimal num = new BigDecimal(quantity);//quantity 从int转换为BigDecimal
            price = price.multiply(num);//计算price = price * num

            cart.incrementQuantityByItemId(workingItemId);
            //持久化数量，保存至数据库中
            cartService.incrementQuantityByItemId(account.getUsername(), workingItemId, quantity, price);

        } else {
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            if (isInStock) {
                Item item = catalogService.getItem(workingItemId);
                cart.addItem(item, isInStock);
                //增加购物车项，保存至数据库中
                cartService.insertCartItem(account.getUsername(), item);
            }
        }
        model.addAttribute("cart", cart);
        Iterator<CartItem> cartItem= cart.getAllCartItems();
        model.addAttribute("cartItem", cartItem);
        return "/cart/Cart";
    }

    @GetMapping("/removeItemFromCart")
    public String removeItemFormCart(HttpSession session, String workingItemId, Model model) {
        Account account = (Account)session.getAttribute("account");
        //从购物车中寻找该物品
        Item item = cart.removeItemById(workingItemId);
        //在数据库中也同时删除该物品，持久化保存
        cartService.removeItemById(account.getUsername(), workingItemId);
        if (item == null) {
            //删除成功
            return "/catalog/viewMain";
        } else {
            //更新购物车，并跳转查看
            model.addAttribute("cart", cart);
            Iterator<CartItem> cartItem= cart.getAllCartItems();
            model.addAttribute("cartItem", cartItem);
            return "/cart/Cart";
        }
    }

//    @GetMapping("/updateCartQuantities")
//    public String updateCartQuantities(HttpSession session, int quantity, String itemId, Cart cart, Model model) {
//        Account account = (Account) session.getAttribute("account");
//
//        Iterator<CartItem> cartItems = cart.getAllCartItems();
//        while (cartItems.hasNext()) {
//            CartItem cartItem = (CartItem) cartItems.next();
//            try {
//                if (itemId.equals(cartItem.getItem().getItemId())) {
//                    cart.setQuantityByItemId(itemId, quantity);
//                }
//                if (quantity < 1) {
//                    cartItems.remove();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        model.addAttribute("cart", cart);
//        Iterator<CartItem> cartItemIterator = cart.getAllCartItems();
////        model.addAttribute("cartItem", cartItemIterator);
//        return "/cart/viewCart";
//    }

    @PostMapping("/autoCartQuantity")
    @ResponseBody
    public void autoCartQuantity(HttpServletResponse response, HttpSession session, String itemId, String quantity, Model model) throws IOException {
        Account account = (Account) session.getAttribute("account");
        CartRes cartRes = new CartRes();
        CartItem cartItem = new CartItem();
        cart = (Cart) session.getAttribute("cart");
        int Quantity = Integer.parseInt(quantity);
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        Item item = catalogService.getItem(itemId);
        BigDecimal value = BigDecimal.valueOf(Quantity);
        BigDecimal total =item.getListPrice().multiply(value);
        //前端修改
        cart.setQuantityByItemId(itemId, Quantity);
        //在数据库中修改，保存
        cartService.updateQuantityByItemidAndUserid(account.getUsername(), itemId, Quantity);
        cartService.updateTotalByItemidAndUserid(account.getUsername(), itemId, total);

        while (cartItems.hasNext()) {
            cartItem = (CartItem) cartItems.next();
            if (cartItem.getItem().getItemId().equals(itemId)) {
                break;
            }
        }
        if (Quantity < 1) {
            cartItems.remove();
            //前端修改
            cart.removeItemById(cartItem.getItem().getItemId());
            //在数据库中修改，保存
            cartService.removeItemById(account.getUsername(), itemId);
        }
        cartRes.setTotal(cartItem.getTotal());
        cartRes.setSubtotal(cart.getSubTotal());

        //发送数据到服务端
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        String str = JSON.toJSONString(cartRes);
        out.print(str);
        out.flush();
        out.close();
    }
}
